﻿//=====================================================
// Copyright © 2017-2018 xuxuzhaozhao
// All rights reserved
// GUID: 1f79efb0-92eb-43c3-81fe-efd394a84441
// CLR版本: 4.0.30319.42000
// 新建项输入的名称: BlogService
// 机器名称: WIN10-20170502F
// 注册组织名: 成都名门汇科技有限公司（谊诚科技）
// 命名空间名称: UnitTestingWebAPI.Services
// 文件名: BlogService
// 当前系统时间: 2017/10/21 17:33:37
// 当前登录用户名: xuxuzhaozhao
//======================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnitTestingWebAPI.Data.Infrstucture;
using UnitTestingWebAPI.Data.Repositories;
using UnitTestingWebAPI.Domain;

namespace UnitTestingWebAPI.Services
{
    // operations you want to expose
    public interface IBlogService
    {
        IEnumerable<Blog> GetBlogs(string name = null);
        Blog GetBlog(int id);
        Blog GetBlog(string name);
        void CreateBlog(Blog blog);
        void UpdateBlog(Blog blog);
        void SaveBlog();
        void DeleteBlog(Blog blog);
    }

    public class BlogService : IBlogService
    {
        private readonly IBlogRepository _blogsRepository;
        private readonly IUnitOfWork _unitOfWork;

        public BlogService(IBlogRepository blogsRepository, IUnitOfWork unitOfWork)
        {
            this._blogsRepository = blogsRepository;
            this._unitOfWork = unitOfWork;
        }

        #region IBlogService Members

        public IEnumerable<Blog> GetBlogs(string name = null)
        {
            if (string.IsNullOrEmpty(name))
                return _blogsRepository.GetAll();
            else
                return _blogsRepository.GetAll().Where(c => c.Name == name);
        }

        public Blog GetBlog(int id)
        {
            var blog = _blogsRepository.GetById(id);
            return blog;
        }

        public Blog GetBlog(string name)
        {
            var blog = _blogsRepository.GetBlogByName(name);
            return blog;
        }

        public void CreateBlog(Blog blog)
        {
            _blogsRepository.Add(blog);
        }

        public void UpdateBlog(Blog blog)
        {
            _blogsRepository.Update(blog);
        }

        public void DeleteBlog(Blog blog)
        {
            _blogsRepository.Delete(blog);
        }

        public void SaveBlog()
        {
            _unitOfWork.Commit();
        }

        #endregion
    }
}
